<template>
    <div v-loading="loading">
        <b-table
            ref="table"
            :columns="columns"
            :scroll="{ x: 1300 }"
            :request="loadData"
            :export-config="{ use: true, select: '租赁费用明细', all: '租赁费用明细' }"
        >
            <template v-if="state !== 3" slot="prefix" slot-scope="ref">
                <a-button type="primary" @click="openDailog"> 添加行 </a-button>
                <a-button @click="ref.delete(delFunc)"> 删除行 </a-button>
                <!--<ExcelImportButton @handleSubmit="importFunc"></ExcelImportButton>-->
            </template>
            <template v-if="state !== 3" slot="suffix">
                <export-mould
                    style="margin-left: 5px"
                    button-text="标准模板下载"
                    template-code="租赁费结算单.xlsx"
                    icon="cloud-download"
                />
                <ExcelImportButton button-text="批量导入" icon="upload" @handleSubmit="importFunc" />
            </template>
            <span slot="index" slot-scope="text, record, index">{{ index + 1 }}</span>
            <div
                v-for="(col, i) in [
                    'materialNum',
                    'startDate',
                    'endDate',
                    'isFloatHalfDayStr',
                    'leaseDays',
                    'priceExTax',
                    'taxTypeName',
                    'priceWithTax',
                    'settleAmountWithoutTax',
                    'settleAmountWithTax',
                    'remark'
                ]"
                :slot="col"
                :key="i"
                slot-scope="text, record, index"
            >
                <!--<template v-if="index === editingIndex">-->
                <template v-if="state !== 3">
                    <a-date-picker
                        v-if="col === 'startDate'"
                        v-model="record[col]"
                        v-check="col"
                        :class="{ tableInputBg: col === 'startDate' }"
                        value-format="YYYY-MM-DD"
                        @change="(e) => handleChange(e, record)"
                    />
                    <a-date-picker
                        v-else-if="col === 'endDate'"
                        v-model="record[col]"
                        v-check="col"
                        :class="{ tableInputBg: col === 'endDate' }"
                        value-format="YYYY-MM-DD"
                        @change="(e) => handleChange(e, record)"
                    />
                    <a-select
                        v-else-if="col === 'taxTypeName'"
                        v-model="record['taxTypeId']"
                        v-check="col"
                        :class="{ tableInputBg: col === 'taxTypeName' }"
                        @change="(e) => handleChange(e, record)"
                    >
                        <a-select-option v-for="item in rateArr" :key="item.id" :value="item.id">
                            {{ item.name }}
                        </a-select-option>
                        {{ record }}
                    </a-select>
                    <a-select
                        v-else-if="col === 'isFloatHalfDayStr'"
                        v-model="record['floatHalfDay']"
                        v-check="col"
                        :class="{ tableInputBg: col === 'isFloatHalfDayStr' }"
                        @change="(e) => handleChange(e, record)"
                    >
                        <a-select-option :value="true"> 是 </a-select-option>
                        <a-select-option :value="false"> 否 </a-select-option>
                    </a-select>
                    <BaseInput
                        v-else-if="col === 'remark'"
                        v-model="record[col]"
                        v-check="col"
                        @blur="(e) => handleChange(e.target.value, record)"
                    />
                    <BaseInputNumber
                        v-else-if="col === 'materialNum'"
                        v-model="record[col]"
                        v-check="col"
                        :class="{ tableInputBg: col === 'materialNum' }"
                        :precision="3"
                        :disabled="
                            col === 'leaseDays' ||
                            col === 'priceWithTax' ||
                            col === 'settleAmountWithoutTax' ||
                            col === 'settleAmountWithTax'
                        "
                        @blur="(e) => handleChange(e, record)"
                    />
                    <BaseInputNumber
                        v-else-if="col === 'priceExTax' || col === 'priceWithTax'"
                        v-model="record[col]"
                        v-check="col"
                        :class="{ tableInputBg: col === 'priceExTax' }"
                        :precision="2"
                        :disabled="
                            col === 'leaseDays' ||
                            col === 'priceWithTax' ||
                            col === 'settleAmountWithoutTax' ||
                            col === 'settleAmountWithTax'
                        "
                        @change="(e) => handleChange(e, record)"
                    />
                    <BaseInputNumber
                        v-else
                        v-model="record[col]"
                        v-check="col"
                        :disabled="
                            col === 'leaseDays' ||
                            col === 'priceWithTax' ||
                            col === 'settleAmountWithoutTax' ||
                            col === 'settleAmountWithTax'
                        "
                        @blur="(e) => handleChange(e, record)"
                    />
                </template>
                <template v-else>
                    {{ text }}
                </template>
            </div>
            <!--<template slot="operation" slot-scope="text, record, index">-->
            <!--<div class="editable-row-operations">-->
            <!--<span v-if="index === editingIndex">-->
            <!--<a @click="save(record)">保存</a>-->
            <!--<a @click="cancel(record)">取消</a>-->
            <!--</span>-->
            <!--<span v-else>-->
            <!--<a :disabled="editingIndex !== null || state === 3" @click="editingIndex = index">编辑</a>-->
            <!--</span>-->
            <!--</div>-->
            <!--</template>-->
        </b-table>
        <!--<material-list ref="detailDialog" @createList="createList"-->
        <!--:urlFun="materialDialogList" :other-data="{contractId:contractId,settleId:id}"></material-list>-->
        <materialListAndDir
            ref="detailDialog"
            :mode="'single'"
            :api="materialDialogList"
            :request-params="{ contractId: contractId, settleId: id }"
            @createList="createList"
        />
    </div>
</template>
<script>
import {
    leaseDetailList,
    leaseDetailDel,
    leaseDetailAdd,
    materialDialogList,
    leaseDetailEdit,
    exportByDetailsLease,
    createLeases
} from '@/api/material/settlement/settlement'
import { columns } from './insideModel'
import { selectOption } from '@/api/material/goods/goods'
import ExportMould from '@/components/ExportMould'
import materialListAndDir from '@/components/materialListAndDir/materialListAndDir'
export default {
    components: {
        ExportMould,
        materialListAndDir
    },
    props: {
        state: {
            type: Number
        },
        id: {
            type: String
        },
        contractId: {
            type: String
        }
    },
    data() {
        return {
            loading: false,
            columns: columns,

            materialDialogList: materialDialogList,
            rateArr: [],
            delFunc: leaseDetailDel,
            loadData: (params) => leaseDetailList({ ...params, settleId: this.id }),
            rules: {
                materialNum: { rule: 'required', message: '租赁数量不能为空' },
                startDate: { rule: 'required', message: '本期计算起始日期不能为空' },
                endDate: { rule: 'required', message: '本期计算终止日期不能为空' },
                floatHalfDay: { rule: 'required', message: '是否浮动半天不能为空' },
                priceExTax: { rule: 'required', message: '不含税单价不能为空' },
                taxTypeId: { rule: 'required', message: '税率不能为空' }
            },
            editingIndex: null,
            checkKeys: new Map()
        }
    },
    directives: {
        check: {
            inserted(el, binding, vNode) {
                if (vNode.context.rules[binding.value]) {
                    let rule = vNode.context.rules[binding.value]
                    vNode.context.checkKeys.set(binding.value, rule.message)
                }
            }
        }
    },
    mounted: function () {
        if (this.state === 3) {
            this.editingIndex = null
        }
        this.getRate()
    },
    methods: {
        async importFunc(e) {
            let newTable = [],
                newTableTit = [],
                colEmpty = [],
                emptyTip = '',
                noneColArr = []
            e.map((row, num) => {
                let temp = {}
                newTableTit[num] = []
                for (const rowKey in row) {
                    newTableTit[num].push(rowKey)
                    let column = this.columns.find((columnRow) => columnRow.title === rowKey)
                    if (column) {
                        let dataIndex = column.dataIndex
                        if (dataIndex === 'isFloatHalfDayStr') {
                            temp.floatHalfDay = row[rowKey] === '是' ? true : false
                        } else {
                            temp[dataIndex] = row[rowKey]
                        }
                    }
                }
                temp.settleId = this.id
                newTable.push(temp)
                //验证未填项
                let col = [
                    '物料名称',
                    '物料编码',
                    '规格型号',
                    '计量单位',
                    '租赁数量',
                    '本期计算起始时间',
                    '本期计算结束时间',
                    '是否浮动半天',
                    '不含税单价（元）',
                    '税率'
                ]
                noneColArr[num] = []
                col.forEach((item, index) => {
                    let status = newTableTit[num].includes(item)
                    if (!status) {
                        noneColArr[num].push(item)
                    }
                })
                if (noneColArr[num].length > 0) {
                    colEmpty[num] = {
                        name: noneColArr[num],
                        num: num + 1
                    }
                }
            })
            if (colEmpty.length > 0) {
                for (let item in colEmpty) {
                    emptyTip += '第' + colEmpty[item].num + '行：' + colEmpty[item].name + '\r\n'
                }
                emptyTip = '请完整输入内容：\r\n' + emptyTip
                this.$notification.open({ message: '提示', duration: null, description: () => <pre>{emptyTip}</pre> })
                return false
            }
            try {
                this.loading = true
                let res = await exportByDetailsLease(newTable)
                let msg = res.message
                this.loading = false
                this.$refs.table.getData(null, true)
                this.$notification.open({ message: '提示', duration: null, description: () => <pre>{msg}</pre> })
            } catch (e) {
                this.loading = false
            }
        },
        async getRate() {
            let res = await selectOption({ type: 21 })
            if (res.code === 200) {
                this.rateArr = res.data
            }
        },
        openDailog: function () {
            if (this.editingIndex !== null) {
                this.$message.error('新增前请结束当前操作行')
                return
            }
            this.$refs.detailDialog.open()
        },
        createList: function (selectRow) {
            selectRow.map((item) => {
                item.settleId = this.id
            })
            createLeases(selectRow).then((res) => {
                if (res.code === 200) {
                    // this.cancel()
                    this.$refs.table.getData(null, true)
                }
            })
        },
        handleChange(value, target) {
            this.rateArr.map(function (item) {
                if (target.taxTypeId === item.id) {
                    let num = item.name.replace('%', '')
                    num = num / 100
                    target['priceWithTax'] = target['priceExTax'] * (1 + num)
                    return
                }
            })
            let end = new Date(target['endDate']).getTime()
            let start = new Date(target['startDate']).getTime()
            if (start && end) {
                if (start > end) {
                    this.$message.error('本期计算终止日期不能小于本期计算起始日期')
                    return
                }
            }
            if (target['floatHalfDay'] != null) {
                target['isFloatHalfDayStr'] = target['floatHalfDay'] ? '是' : '否'
            }
            let halfResult = target.floatHalfDay ? 0.5 : 0
            target['leaseDays'] = parseInt((end - start) / (1000 * 60 * 60 * 24)) + 1 - halfResult
            target['settleAmountWithoutTax'] = target['materialNum'] * target['leaseDays'] * target['priceExTax']
            target['settleAmountWithoutTax'] = target['settleAmountWithoutTax'].toFixed(2)
            target['settleAmountWithTax'] = target['materialNum'] * target['leaseDays'] * target['priceWithTax']
            target['settleAmountWithTax'] = target['settleAmountWithTax'].toFixed(2)
            this.save(target, 'state')
        },
        async save(row, state) {
            try {
                // this.checkKeys.forEach((value, key) => {
                //     if (this.$isEmpty(row[key])) throw new Error(value)
                // })
                if (this.compareSize(row['startDate'], row['endDate'], '本期计算终止日期不能小于本期计算起始日期')) {
                    return
                }
                if (!state) {
                    this.loading = true
                }
                let res = await leaseDetailEdit(row)
                if (res.code === this.SUCCESS_CODE) {
                    if (!state) {
                        this.$noticeSuccess('编辑成功')
                    }
                    // this.cancel()
                }
                if (!state) {
                    this.loading = false
                    this.$emit('disabledSub', false)
                }
            } catch (e) {
                if (!state) {
                    this.loading = false
                    this.$emit('disabledSub', false)
                }
            }
        }
        // cancel() {
        //     this.editingIndex = null
        //     this.$refs.table.getData()
        // }
    }
}
</script>
<style scoped>
/deep/ .tableInputBg .ant-input-number,
/deep/ .tableInputBg .ant-calendar-picker-input,
/deep/ .tableInputBg .ant-select-selection {
    background-color: #fff9e8;
    border: 1px solid #e4ac0b;
}
</style>